package com.pl.config.security.oauth2;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.filter.GenericFilterBean;

import com.google.common.base.Objects;

/**
 * class name:MySecurityContextPersistenceFilter <BR>
 * class 第一次打开客户端页面，重定向到认证端，认证后，认证端会记住你，所以第二次打开客户端会自动登录
 *       所以在这里判断，如果再次客户端重定向，注销当前session，防止自动登录 <BR>
 * Remark: <BR>
 * @version 1.00 2019年11月30日
 * @author wangjian
 */
public class MySecurityContextPersistenceFilter extends GenericFilterBean{
	
	private RequestCache requestCache = new HttpSessionRequestCache();
	
	protected final Log logger = LogFactory.getLog(getClass());

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
//		String url = request.getRequestURI();
//		System.out.println(request.getRequestURI());
		
//		System.out.println("selfFrom=" + request.getParameter("selfFrom"));
		
//		if(request.getRequestURI().equals(request.getContextPath() + "/oauth/authorize")) {
//			//重定向的URL
//			try {
//				HttpSession session = request.getSession(false);
//				
//				if(session !=null) {
//					// 没有savedRequest，即没有客户端的回调地址，即客户端刚来请求，后面的方法没有写入savedRequest
//					SavedRequest savedRequest = requestCache.getRequest(request, response);
//					if(savedRequest == null && !Objects.equal(request.getParameter("selfFrom"), "server")) {
//						//session.removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
//						//如果 selfFrom == "server"，认证中心，直接去客户端，不能删除认证信息
//						session.invalidate();
//					}
//				}
//
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}

		chain.doFilter(req, res);
	}
	
	
}
